<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="城市标签" prop="cityName">
        <el-select
          v-model="queryParams.cityName"
          @change="handleQuery"
          filterable
          fit-input-width
          placeholder="请选择"
        >
          <el-option
            v-for="item in cityNameOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="券包名称" prop="packName">
        <el-input
          style="width: 200px"
          maxlength="16"
          v-model.trim="queryParams.packName"
          placeholder="请输入优惠券名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="">
        <div class="btn-group">
          <el-button plain v-hasPermi="['org:couponPack:export']" @click="handleExport">
            导出数据
          </el-button>

          <el-radio-group v-model="radioValue" @change="handleDateRange" style="flex-shrink: 0">
            <el-radio-button label="当天" />
            <el-radio-button label="最近7天" />
            <el-radio-button label="最近30天" />
          </el-radio-group>

          <el-date-picker
            v-model="state.timeRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="dateChange"
            :clearable="false"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="state.loading" size="default" index :data="dataList">
      <el-table-column label="券包名称" align="center" prop="packName">
        <template #default="{ row }">
          <div>
            <el-link
              :underline="false"
              type="primary"
              :disabled="!hasPermi(['org:couponPack:detail'])"
              @click="handleDetail(row)"
              >{{ row.packName }}</el-link
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column label="投放份数" align="center" prop="totalCopiesDistributed" />
      <el-table-column label="已售份数" align="center" prop="soldCopies" />
      <el-table-column label="未售份数" align="center" prop="unsoldCopies" />
      <el-table-column label="售卖率" align="center" prop="salesRate">
        <template #default="{ row }"> {{ row.salesRate || 0 }}% </template>
      </el-table-column>
      <el-table-column label="已售总金额(元)" align="center" prop="totalSalesAmount" />
    </el-table>
    <div style="margin-right: 10px">
      <pagination
        v-show="state.total > 0"
        :total="state.total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <detailList ref="detailListRef"></detailList>
  </div>
</template>

<script setup>
import useGlobalStore from '@/store/modules/global'
import { hasPermi } from '@/utils/tools'
import detailList from './components/detailList.vue'
import { parseTime } from '@/utils/tools'
import { getPackSalesListApi } from '@/api/statistic'
import { onMountedOrActivated } from '@/hooks/common'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
// =============== ==============
const queryRef = ref(null)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  cityName: cityNameOptions.value[0]
})
const dataList = ref([])
const state = reactive({
  total: 0,
  loading: false,
  timeRange: [
    parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00:00',
    parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  ]
})

// ======================= 搜索 ======================
async function getList() {
  state.loading = true
  const [startDate, endDate] = state.timeRange
  queryParams.startDate = startDate ? startDate : ''
  queryParams.endDate = endDate ? endDate : ''
  try {
    const r = await getPackSalesListApi(queryParams)
    dataList.value = r?.data?.rows || []
    state.total = r?.data?.total ?? 0
  } finally {
    state.loading = false
  }
}
// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  queryRef.value.resetFields()
  radioValue.value = '当天'
  handleDateRange('当天')
}

const radioValue = ref('当天')

const dateChange = () => {
  radioValue.value = ''
  handleQuery()
}
function handleDateRange(val) {
  const end = parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  const start = new Date()
  switch (val) {
    case '最近30天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '最近7天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '当天':
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    default:
      break
  }
  handleQuery()
}

// 导出
const { proxy } = getCurrentInstance()
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'operation/statistics/admin/pack-sales/export',
    queryParams,
    `券包销售数据${new Date().getTime()}.xlsx`
  )
}

// 券包详情
const detailListRef = ref(null)
function handleDetail(row) {
  detailListRef.value.init(row, queryParams)
}
/**init +  onActivated*/
onMountedOrActivated(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  handleQuery()
})
</script>

<style lang="scss" scoped>
.app-container {
  min-width: 960px;
  overflow-x: auto;
}
.btn-group {
  display: flex;
  align-items: center;
}
.el-radio-group {
  margin: 0 10px;
}
</style>
